import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  NavBar,
  Tabs,
  Image,
  Button,
  Empty,
  Space,
  Toast,
  Dialog,
  Ellipsis
} from 'antd-mobile';
import './OrderList.css';
import { useRequest } from 'ahooks';
import { getOrders } from '../../api/dashboard';
import { cancelOrder, updateOrder } from '../../api/store';
// 订单列表页面
const OrderList = () => {
  const navigate = useNavigate();
  const location = useLocation();
  // 从会话存储中获取上次选择的标签页，如果没有则默认为'all'
  const [activeTab, setActiveTab] = useState(sessionStorage.getItem('orderListActiveTab') || 'all');
  const [orders, setOrders] = useState([]);
  const [filteredOrders, setFilteredOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const prevPathRef = useRef('');
  const initialLoadRef = useRef(true);

  const { runAsync: getOrdersAsync } = useRequest(getOrders, { manual: true });
  const { runAsync: updateOrderAsync } = useRequest(updateOrder, { manual: true });
  const { runAsync: cancelOrderAsync } = useRequest(cancelOrder, { manual: true });
  // 当标签页变化时，保存到会话存储中
  useEffect(() => {
    sessionStorage.setItem('orderListActiveTab', activeTab);
  }, [activeTab]);

  // 检测从订单详情页返回，并刷新页面
  useEffect(() => {
    // 检查是否是首次加载
    if (initialLoadRef.current) {
      initialLoadRef.current = false;

      // 设置一个标记到sessionStorage，表示页面已加载
      const fromDetailFlag = sessionStorage.getItem('fromOrderDetail');
      if (fromDetailFlag === 'true') {
        // 清除标记
        sessionStorage.removeItem('fromOrderDetail');
        // 刷新页面
        window.location.reload();
        return;
      }
    }

    // 保存当前路径
    prevPathRef.current = location.pathname;
  }, [location]);

  // 获取订单数据
  const fetchOrders = async () => {
    setLoading(true);

    // 从本地存储获取订单数据
    const storedOrders = await getOrdersAsync({ params: { id: 1 } });

    // 按照创建时间降序排序
    const sortedOrders = storedOrders.sort((a, b) => {
      return new Date(b.createTime) - new Date(a.createTime);
    });

    setOrders(sortedOrders);
    setLoading(false);
  };

  // 初始加载和路由变化时获取数据
  useEffect(() => {
    // 检查用户是否登录
    const userInfo = localStorage.getItem('userInfo');
    if (!userInfo) {
      navigate('/login');
      return;
    }

    fetchOrders();
  }, [navigate, location]);

  // 根据标签筛选订单
  useEffect(() => {
    if (activeTab === 'all') {
      setFilteredOrders(orders);
    } else {
      const filtered = orders.filter(order => {
        switch (activeTab) {
          case 'pending':
            return order.status === 'pending';
          case 'paid':
            return order.status === 'paid';
          case 'shipped':
            return order.status === 'shipped';
          case 'completed':
            return order.status === 'completed';
          default:
            return true;
        }
      });
      setFilteredOrders(filtered);
    }
  }, [activeTab, orders]);

  // 处理取消订单
  const handleCancelOrder = (orderId) => {
    Dialog.confirm({
      content: '确认取消该订单吗？',
      onConfirm: async () => {
        // 更新订单状态
        const res = await cancelOrderAsync({ id: orderId });
        // 更新当前订单状态
        setOrders(res.orders);

        Toast.show({
          icon: 'success',
          content: '订单已取消',
        });
      },
    });
  };

  // 处理删除订单
  const handleDeleteOrder = (orderId) => {
    Dialog.confirm({
      content: '确认删除该订单吗？删除后无法恢复',
      onConfirm: () => {
        const updatedOrders = orders.filter(o => o.id !== orderId);
        localStorage.setItem('orders', JSON.stringify(updatedOrders));
        setOrders(updatedOrders);

        Toast.show({
          icon: 'success',
          content: '订单已删除',
        });
      },
    });
  };

  // 处理确认收货
  const handleConfirmReceipt = (orderId) => {
    Dialog.confirm({
      content: '确认已收到商品吗？',
      onConfirm: async () => {
        try {
          // 直接更新指定订单状态
          await updateOrderAsync({
            id: orderId,
            status: 'completed',
            completionTime: new Date().toISOString(),
            receiptConfirmTime: new Date().toISOString()
          });

          // 更新本地订单状态
          setOrders(prevOrders =>
            prevOrders.map(order =>
              order.id === orderId
                ? {
                  ...order,
                  status: 'completed',
                  completionTime: new Date().toISOString(),
                  receiptConfirmTime: new Date().toISOString()
                }
                : order
            )
          );

          Toast.show({
            icon: 'success',
            content: '已确认收货，感谢您的购买！',
          });
        } catch (error) {
          console.error('确认收货失败:', error);
          Toast.show({
            icon: 'fail',
            content: '确认收货失败，请重试',
          });
        }
      },
    });
  };

  // 获取订单状态文本
  const getOrderStatusText = (status) => {
    switch (status) {
      case 'pending':
        return '待付款';
      case 'paid':
        return '待发货';
      case 'shipped':
        return '待收货';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知状态';
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  // 渲染订单操作按钮
  const renderOrderActions = (order) => {
    // 使用React.memo和useMemo的思想，避免不必要的重渲染
    const actionKey = `${order.id}-${order.status}`;

    switch (order.status) {
      case 'pending':
        return (
          <Space className="order-actions" key={actionKey}>
            <Button
              size='small'
              onClick={() => handleCancelOrder(order.id)}
            >
              取消订单
            </Button>
            <Button
              size='small'
              color='primary'
              onClick={() => navigate(`/order/payment/${order.id}`)}
            >
              去支付
            </Button>
          </Space>
        );
      case 'paid':
        return (
          <Space className="order-actions" key={actionKey}>
            <Button
              size='small'
              onClick={() => {
                // 设置标记，表示从详情页返回
                sessionStorage.setItem('fromOrderDetail', 'true');
                navigate(`/order/detail/${order.id}`);
              }}
            >
              查看详情
            </Button>
          </Space>
        );
      case 'shipped':
        return (
          <Space className="order-actions" key={actionKey}>
            <Button
              size='small'
              onClick={() => {
                // 设置标记，表示从详情页返回
                sessionStorage.setItem('fromOrderDetail', 'true');
                navigate(`/order/detail/${order.id}`);
              }}
            >
              查看物流
            </Button>
            <Button
              size='small'
              color='primary'
              onClick={() => handleConfirmReceipt(order.id)}
            >
              确认收货
            </Button>
          </Space>
        );
      case 'completed':
        return (
          <Space className="order-actions" key={actionKey}>
            <Button
              size='small'
              color='primary'
              onClick={() => Toast.show('评价功能开发中')}
            >
              评价商品
            </Button>
            <Button
              size='small'
              onClick={() => navigate('/home')}
            >
              再次购买
            </Button>
          </Space>
        );
      case 'cancelled':
        return (
          <Space className="order-actions" key={actionKey}>
            <Button
              size='small'
              onClick={() => handleDeleteOrder(order.id)}
            >
              删除订单
            </Button>
            <Button
              size='small'
              onClick={() => navigate('/home')}
            >
              继续购物
            </Button>
          </Space>
        );
      default:
        return null;
    }
  };

  // 返回上一页
  const back = () => {
    navigate(-1);
  };

  return (
    <div className="order-list-container">
      {/* 导航栏 */}
      <NavBar onBack={back}>我的订单</NavBar>

      {/* 标签页 */}
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        className="order-tabs"
      >
        <Tabs.Tab title="全部" key="all" />
        <Tabs.Tab title="待付款" key="pending" />
        <Tabs.Tab title="待发货" key="paid" />
        <Tabs.Tab title="待收货" key="shipped" />
        <Tabs.Tab title="已完成" key="completed" />
      </Tabs>

      {/* 订单列表 */}
      <div className="order-list-content">
        {loading ? (
          <div className="loading-container">
            <div className="loading-spinner">加载中...</div>
          </div>
        ) : filteredOrders.length === 0 ? (
          <Empty
            description="暂无订单"
            className="empty-order"
          />
        ) : (
          <div className="order-list">
            {filteredOrders.map(order => (
              <div key={`order-${order.id}-${order.status}`} className="order-item-card">
                <div className="order-header">
                  <div className="order-time">
                    {formatDate(order.createTime)}
                  </div>
                  <div className="order-status" data-status={order.status}>
                    {getOrderStatusText(order.status)}
                  </div>
                </div>

                <div
                  className="order-content"
                  onClick={() => {
                    // 设置标记，表示从详情页返回
                    sessionStorage.setItem('fromOrderDetail', 'true');
                    navigate(`/order/detail/${order.id}`);
                  }}
                >
                  {order.orderItems.map(item => (
                    <div key={`item-${order.id}-${item.id}`} className="order-product">
                      <Image
                        className="product-image"
                        src={item.image}
                        fit='cover'
                        width={60}
                        height={60}
                      />
                      <div className="product-info">
                        <Ellipsis
                          className="product-name"
                          direction='end'
                          rows={2}
                          content={item.name}
                        />
                        <div className="product-price-qty">
                          <span className="product-price">¥{item.price.toFixed(2)}</span>
                          <span className="product-quantity">x{item.quantity}</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                <div className="order-footer">
                  <div className="order-total">
                    共{order.totalCount}件商品 总计: <span className="total-price">¥{order.totalPrice.toFixed(2)}</span>
                  </div>
                  {renderOrderActions(order)}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default OrderList; 